<template>
  <div>
    <div class="jiantou">
      <i class="el-icon-arrow-left" @click="fanhui"></i>
      <h4>抢单</h4>
    </div>
    <hr>
    <div class="tongji">
      <van-cell title="运营时长" :value="times"/>
      <van-cell title="接单数" :value="num"/>
      <van-cell title="今日流水" :value="money"/>
    </div>
    <ul class="infinite-list" style="overflow:auto">
      <div class="shishi" v-for="order in list" v-if="order.orderType==1">
        <h4>实时单</h4>
        <hr>
        <div class="qi">
          <div class="lvd"></div>
          <p class="dizhi">{{ order.startingPoint }}</p>
        </div>
        <div class="zhong">
          <div class="huangd"></div>
          <p class="dizhi">{{ order.terminal }}</p>
        </div>
        <p class="beizhu">备注：订单备注</p>
        <hr>
        <!-- 显示计算出的距离 -->
        <p class="juli">到起点距离：<span>{{
            distanceToOrderStarting ? distanceToOrderStarting.toFixed(2) : '计算中...'
          }}</span>km</p>
        <p class="juli"><i class="el-icon-location"></i>距您<span style="color: blue">{{ order.distance }}</span>km</p>
        <p class="chefei">预估<span style="color: red">￥{{ order.prices }}</span></p>
        <el-button type="primary" :disabled="isButtonDisabled" @click="open(order.id)"
                   v-if="distanceToOrderStarting <= 3">接单
        </el-button>
        <el-button type="primary" :disabled="isButtonDisabled" @click="open2(order.id)"
                   v-if="distanceToOrderStarting > 3">接单
        </el-button>
      </div>
    </ul>
    <ul class="infinite-list" style="overflow:auto">
      <div class="shishi" v-for="order in list" v-if="order.orderType==0">
        <h4>预约单</h4>
        <hr>
        <div class="qi">
          <div class="lvd"></div>
          <p class="dizhi">{{ order.startingPoint }}</p>
        </div>
        <div class="zhong">
          <div class="huangd"></div>
          <p class="dizhi">{{ order.terminal }}</p>
        </div>
        <p class="beizhu">备注：订单备注</p>
        <hr>
        <!-- 显示计算出的距离 -->
        <p class="juli">到起点距离：<span>{{
            distanceToOrderStarting ? distanceToOrderStarting.toFixed(2) : '计算中...'
          }}</span>km</p>
        <p class="juli"><i class="el-icon-location"></i>距您<span style="color: blue">{{ order.distance }}</span>km</p>
        <p class="chefei">预估<span style="color: red">￥{{ order.prices }}</span></p>
        <el-button type="primary" :disabled="isButtonDisabled" @click="open(order.id)"
                   v-if="distanceToOrderStarting <= 3">接单
        </el-button>
        <el-button type="primary" :disabled="isButtonDisabled" @click="open2(order.id)"
                   v-if="distanceToOrderStarting > 3">接单
        </el-button>
      </div>
    </ul>
    <div class="bottom">
      <el-button class="shuaxin">刷新</el-button>
      <el-button class="tingdan">听单中...</el-button>
      <el-button class="xiuxi" @click="toXiuxi">休息</el-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";

function getDistance(lat1, lon1, lat2, lon2) {
  const R = 6371; // 地球平均半径，单位为公里
  const dLat = (lat2 - lat1) * (Math.PI / 180);
  const dLon = (lon2 - lon1) * (Math.PI / 180);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

export default {
  data() {
    return {
      list: {},
      num: "",
      driverInfo: {},
      tel: '',
      money: "",
      times: "",
      orderId: "",
      cid: 0,
      cid2: "",
      pollingTimer: null,
      latitude: 40.21813347249725, // 设置默认纬度值
      longitude: 116.21720503656424, // 设置默认经度值
      orderStartingLatitude: null, // 订单起点纬度
      orderStartingLongitude: null, // 订单起点经度
      orderTerminalLatitude: null, // 订单终点纬度
      orderTerminalLongitude: null, // 订单终点经度
      distanceToOrderStarting: null, // 存储司机位置到订单起点的距离
      isButtonDisabled: false // 用于控制按钮是否禁用
    };
  },
  methods: {
    // 根据手机号查询到司机id
    async findDriverByTel() {
      const tel = JSON.parse(localStorage.getItem('login'));
      const response = await axios.post('personal/personal/findByTel?tel=' + tel);
      this.driverInfo = response.data;
      console.log(this.driverInfo);
      return this.driverInfo;
    },
    // 根据id查询订单数
    async jiedanshu() {
      if (!this.driverInfo.id) {
        console.error('司机信息未获取到，无法查询订单数');
        return;
      }
      const response = await axios.post(`order/order/jiedanNum?id=${this.driverInfo.id}`);
      this.num = response.data;
    },
    // 根据司机查流水
    async liushui() {
      if (!this.driverInfo.id) {
        console.error('司机信息未获取到，无法查询流水');
        return;
      }
      const response = await axios.post(`order/order/liushuimoney?id=${this.driverInfo.id}`);
      this.money = response.data;
    },
    // 根据司机id查询运营时长
    async yunyingshichang() {
      if (!this.driverInfo.id) {
        console.error('司机信息未获取到，无法查询运营时长');
        return;
      }
      const response = await axios.post(`order/order/yunyingshichang?id=${this.driverInfo.id}`);
      this.times = response.data;
    },
    open2(id) {
      this.isButtonDisabled = true; // 点击按钮后先禁用按钮
      alert("订单id:" + id);
      this.$confirm('该订单距离您超过3公里，请确认是否接单？', '提醒', {
        confirmButtonText: '确认订单',
        cancelButtonText: '我再想想',
        type: 'warning'
      }).then(() => {
        axios.post("jiedan/riderQueue/updateDriverId?id=" + id + "&did=" + this.driverInfo.id).then(res => {
          this.$message({
            type: 'success',
            message: '确认!',
          });
          this.tostarting(id);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '我再想想'
        });
      }).finally(() => {
        setTimeout(() => {
          this.isButtonDisabled = false; // 操作完成（无论成功失败）后，经过一定延迟再启用按钮
        }, 1000); // 这里设置 1 秒的延迟，可根据实际情况调整
      });
    },
    open(id) {
      this.isButtonDisabled = true; // 点击按钮后先禁用按钮
      alert("订单id:" + id);
      this.$confirm('请确保电量充足，可以完成订单否则将产生违约金', '提醒', {
        confirmButtonText: '确认订单',
        cancelButtonText: '我再想想',
        type: 'warning'
      }).then(() => {
        axios.post("jiedan/riderQueue/updateDriverId?id=" + id + "&did=" + this.driverInfo.id).then(res => {
          this.$message({
            type: 'success',
            message: '确认!',
          });
          this.tostarting(id);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '我再想想'
        });
      }).finally(() => {
        setTimeout(() => {
          this.isButtonDisabled = false; // 操作完成（无论成功失败）后，经过一定延迟再启用按钮
        }, 1000); // 这里设置 1 秒的延迟，可根据实际情况调整
      });
    },
    tostarting(id) {
      sessionStorage.setItem("id", JSON.stringify(id))
      this.$router.push("/starting")
    },
    toXiuxi(id) {
      axios.post("/order/driver/updateStatus2?id=" + this.driverInfo.id)
      this.$router.push("/shouye")
    },
    fanhui() {
      this.$router.push("/shouye")
    },
    async getCarId() {
      axios.post(`/order/driver/findCarId?id=${this.driverInfo.id}`).then(res => {
        this.cid = res.data;
        sessionStorage.setItem("carid", JSON.stringify(this.cid))
        this.getList(this.cid)

      })
    },
    async getList(cid) {
      axios.get(`jiedan/riderQueue/findAll?id=${cid}`)
        .then((response) => {
          this.list = response.data;
          this.list.forEach(order => {
            if (order.startingPoint && order.useraddssLon && order.useraddssLat) {
              this.orderStartingLatitude = order.useraddssLat;
              this.orderStartingLongitude = order.useraddssLon;
              if (this.latitude && this.longitude) {
                this.distanceToOrderStarting = this.calculateDistanceToOrderStarting();
                console.log("司机位置到乘客位置的距离为:", this.distanceToOrderStarting);
              }
            }
            if (order.terminal && order.terminal.latitude && order.terminal.longitude) {
              this.orderTerminalLatitude = order.terminal.latitude;
              this.orderTerminalLongitude = order.terminal.longitude;
            }
          });
        })
        .catch((error) => {
          console.error("获取数据失败：", error);
        });
    },
    // 获取当前位置经纬度
    getCurrentPosition() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          this.latitude = position.coords.latitude;
          this.longitude = position.coords.longitude;
          console.log('获取到的司机经纬度：', this.latitude, this.longitude);
        }, (error) => {
          console.error('获取位置信息出错：', error);
        });
      } else {
        console.error('浏览器不支持获取地理位置');
      }
    },
    calculateDistanceToOrderStarting() {
      if (this.latitude && this.longitude && this.orderStartingLatitude && this.orderStartingLongitude) {
        const distance = getDistance(this.latitude, this.longitude, this.orderStartingLatitude, this.orderStartingLongitude);
        return distance;
      }
      return null; // 如果缺少必要的经纬度信息，返回 null
    }
  },
  async created() {
    try {
      const driverInfo = await this.findDriverByTel();
      await Promise.all([
        this.jiedanshu(),
        this.liushui(),
        this.yunyingshichang(),
        this.getCarId()
      ]);
      await this.getList();

      const positionPromise = new Promise((resolve, reject) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition((position) => {
            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude;
            console.log('获取到的司机经纬度：', this.latitude, this.longitude);
            resolve();
          }, (error) => {
            console.error('获取位置信息出错：', error);
            reject(error);
          });
        } else {
          console.error('浏览器不支持获取地理位置');
          reject(new Error('浏览器不支持获取地理位置'));
        }
      });

      await positionPromise;

      await this.getList();

      // 启动轮询，可根据实际情况调整时间间隔获取最新数据
      this.pollingTimer = setInterval(() => {
        this.getList(this.cid);
      }, 30000);

    } catch (error) {
      console.error('页面初始化数据获取失败：', error);
    }
  },
  beforeDestroy() {
    // 如果轮询定时器存在，则清除它
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer);
    }
  }
};
</script>
<style scoped>

.shishi {
  width: 350px;
  height: 290px;
  background-color: #ffff;
  border-radius: 15px;
  margin-top: 10px;
  margin-left: 25px;
}

.shishi h4 {
  float: left;
  margin-left: 15px;
}

.shishi hr {
  width: 350px;
  margin: 0 auto;
}

button {
  width: 330px;
}

.shishi button {
  width: 330px;
}

.qi {
  width: 330px;
  height: 40px;
  background-color: #e4f6f6;
  border-radius: 10px;
  margin-top: 10px;
  float: left;
  margin-left: 10px;
}

.zhong {
  width: 330px;
  height: 40px;
  background-color: #d7d7d7;
  border-radius: 10px;
  margin-top: 10px;
  float: left;
  margin-left: 10px;
}

.juli {
  float: left;
  margin-left: 15px;

  i {
    font-size: 20px;
  }
}

.chefei {
  float: right;
  margin-right: 15px;
}

.beizhu {
  float: left;
  margin-left: 15px;
}

.dizhi {
  float: left;
  line-height: 15px;
}

ul {
  width: 400px;
  height: 300px;
  margin-top: 15px;
}

.jiantou {
  float: left;
  margin-top: 10px;
  width: 400px;
  height: 40px;
}

.jiantou i {
  float: left;
  font-size: 20px;
  line-height: 40px;
  margin-left: 10px;
}

.jiantou h4 {
  float: left;
  margin-left: 150px;
}

.tongji {
  float: left;
  width: 400px;
  height: 70px;
}

.tongji h2 {
  width: 120px;
  float: left;
  height: 30px;
  margin-left: 10px;
  margin-top: 5px;
}

.tongji p {
  margin-top: -10px;
  float: left;
  width: 120px;
  margin-left: 10px;
}

.bottom {
  width: 400px;
  height: 50px;
}

.shuaxin {
  width: 85px;
  color: #ffff;
  background-color: coral;
}

.tingdan {
  width: 150px;
  color: #ffff;
  background-color: #52b7fd;
}

.xiuxi {
  width: 85px;
  color: #ffff;
  background-color: #525252;
}

.lvd {
  width: 10px;
  height: 10px;
  float: left;
  background-color: #00ff0b;
  border-radius: 8px;
  margin-top: 16px;
  margin-left: 10px;
  margin-right: 5px;
}

.huangd {
  width: 10px;
  height: 10px;
  float: left;
  background-color: #ffa600;
  border-radius: 8px;
  margin-top: 16px;
  margin-left: 10px;
  margin-right: 5px;
}
</style>
